package com.redis.server.cn.aop;

import com.redis.server.cn.commen.ActionResult;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.UUID;

@Aspect
public class LogAop {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAop.class);
    private ThreadLocal<String> startTime = new ThreadLocal<>();

    /**
     * 定义切面
     * controller下面所有包的所有public方法
     */
    @Pointcut("execution(public * com.redis.server.cn.controller..*.*(..))")
    public void log(){}

    /**
     * 切入点前调用
     * @param joinPoint 切入点
     */
    @Before("log()")
    public void methodStart(JoinPoint joinPoint){
        String uuid = UUID.randomUUID().toString().replace("-","").substring(0,6);
        startTime.set(String.format("%s-%s",uuid,System.currentTimeMillis()));
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        LOGGER.info("-> {}-URL : {}",uuid,request.getRequestURL().toString());
        LOGGER.info("-> {}-HTTP_METHOD : {}",uuid,request.getMethod());
        LOGGER.info("-> {}-IP : {}",uuid,request.getRemoteAddr());
        LOGGER.info("-> {}-CLASS_METHOD : {}",uuid,joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        LOGGER.info("-> {}-ARGS : {}",uuid, Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 返回后调用
     * @param result
     */
    @AfterReturning(returning = "result",pointcut = "log()")
    public void methodEnd(Object result){
        String[] flags = startTime.get().split("-");
        String uuid = flags[0];
        Long stTime = Long.parseLong(flags[1]);
        ActionResult actionResult = (ActionResult)result;
        LOGGER.info("-> {}-RESPONSE : {}-{}",uuid,actionResult.getResponseCode(),actionResult.getMessage());
        LOGGER.info("-> {}-USED : {} ms",uuid,System.currentTimeMillis()-stTime);
    }
}
